package com.xltt.watchclient.module.service;

import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.xltt.watchclient.LogTool;
import com.xltt.watchclient.R;
import com.xltt.watchclient.model.NotificationEntity;
import com.xltt.watchclient.model.SmsBodyEntity;
import com.xltt.watchclient.module.utils.BleUtils;

public class NotificationMonitor extends NotificationListenerService {

    private InnerOutCallReceiver mInnerOutCallReceiver;// 动态监听去电的广播接收器
    private MyPhoneStateListener myPhoneStateListener;// 电话状态监听者
    private TelephonyManager mTelephonyManager;// 电话管理者对象
    private static int mLastCallState = TelephonyManager.CALL_STATE_IDLE;
    private NotificationEntity mPhoneEntity = new NotificationEntity();
    private SMSContentObserver mSMSContentObserver;

    @Override
    public void onCreate() {
        super.onCreate();
        LogTool.d("通知服务onCreate()");
//        killNotificationListenerService();
        initPhoneStateRevice();
    }

    /**
     * 监听电话与短信
     */
    private void initPhoneStateRevice() {
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        myPhoneStateListener = new MyPhoneStateListener();
        mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        mInnerOutCallReceiver = new InnerOutCallReceiver();
        // 手机拨打电话时会发送：android.intent.action.NEW_OUTGOING_CALL的广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
        registerReceiver(mInnerOutCallReceiver, intentFilter);
        mSMSContentObserver = new SMSContentObserver(getApplicationContext(), mSmsHanlder);

    }

    /**
     * 推送短信数据到手表
     */
    private final Handler mSmsHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            SmsBodyEntity body = (SmsBodyEntity) msg.obj;
            NotificationEntity data = new NotificationEntity();
            data.setPkg("com.mms");
            data.setTitle(body.getName());
            data.setText(body.getContent());
            data.setPost(true);//用以区分是post还是removed
            data.setType(2);
            send(data);
        }
    };

    /**
     * 动态注册广播接收器监听去电信息
     */
    class InnerOutCallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取播出的去电号码
            String outPhone = getResultData();
            LogTool.d("outPhone:" + outPhone);
        }
    }


    /**
     * ios来电数据格式：
     * {"content":"来电","messageType":1,"operationTime":1641436893420,"platform":1,
     * "result":1,"serviceId":"com.dialer","title":"137 5106 0445"}
     * ios未接来电数据格式：
     * {"content":"未接来电","messageType":2,"operationTime":1641436941520,"platform":1,
     * "result":1,"serviceId":"com.dialer","title":"137 5106 0445"}
     * 自定义内部类对来电的电话状态进行监听
     */
    class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            if (state == TelephonyManager.CALL_STATE_RINGING) {
                lastPhone = null;
                currentPhoneState = state;
            } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                lastPhoneState = state;
                NotificationEntity msg = new NotificationEntity();
                msg.setPkg("com.dialer");
                msg.setTitle("拒接来电");
                msg.setText("拒接来电");
                msg.setType(1);
                msg.setPost(true);//用以区分是post还是removed
                send(msg);
            } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                currentPhoneState = state;
                NotificationEntity msg = new NotificationEntity();
                msg.setPkg("com.dialer");
                msg.setTitle("拒接来电");
                msg.setText("拒接来电");
                msg.setType(1);
                msg.setPost(true);//用以区分是post还是removed
                send(msg);
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    int currentPhoneState = -1;

    @Override
    public void onDestroy() {
        // 取消来电的电话状态监听服务
        if (mTelephonyManager != null && myPhoneStateListener != null) {
            mTelephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
        // 取消去电的广播监听
        if (mInnerOutCallReceiver != null) {
            unregisterReceiver(mInnerOutCallReceiver);
        }
        super.onDestroy();
    }

    /**
     * 每次启动服务之前把之前的服务kill掉，防止重复的服务起来
     */
    private void killNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationMonitor.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationMonitor.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Bundle extras = sbn.getNotification().extras;
        String notificationPkg = BleUtils.convertPakageName(sbn.getPackageName());// 获取接收消息APP的包名
        String notificationTitle = (String) extras.getString(Notification.EXTRA_TITLE);// 获取接收消息的抬头
        CharSequence notificationContentData = extras.getCharSequence(Notification.EXTRA_TEXT);// 获取接收消息的内容
        LogTool.d("监听到通知数据,notificationPkg = " + notificationPkg + ",notificationTitle = " + notificationTitle + ",notificationContentData = " + notificationContentData);
        if (!BleUtils.isListentNoticationPkg(notificationPkg)) {
            LogTool.d("过滤该应用，package = " + notificationPkg);
            return;
        }
        if ("com.android.mms".equals(notificationPkg) && notificationTitle.equals(getApplication().getString(R.string.mms_warring_message))) {
            LogTool.d("过滤小米手机垃圾通知,造成系统推送垃圾数据到手表问题");
            return;
        }

        LogTool.d("监听到通知数据,notificationPkg = " + notificationPkg + ",notificationTitle = " + notificationTitle + ",notificationContentData = " + notificationContentData);
        if (TextUtils.isEmpty(notificationPkg) || TextUtils.isEmpty(notificationTitle) || TextUtils.isEmpty(notificationContentData)) {
            return;
        }
        String notificationContent = notificationContentData.toString();
        String formatContent = BleUtils.convertContent(getApplication(), notificationPkg, notificationTitle, notificationContent);
        if (TextUtils.isEmpty(formatContent)) {
            return;
        }
        NotificationEntity msg = new NotificationEntity();
        msg.setPkg(notificationPkg);
        msg.setTitle(BleUtils.getNoticationTitle(getApplication(), notificationPkg, notificationTitle, notificationContent));
        msg.setText(formatContent);
        msg.setType(2);
        msg.setPost(true);//用以区分是post还是removed
        if ("com.dialer".equals(notificationPkg)) {
            if (currentPhoneState == TelephonyManager.CALL_STATE_RINGING) {
                currentPhoneState = -1;
                lastPhone = notificationTitle;
                msg.setTitle(notificationTitle);
                msg.setText("来电");
                msg.setType(1);
            } else if (currentPhoneState == TelephonyManager.CALL_STATE_IDLE) {
                msg.setType(2);
                msg.setTitle(lastPhone);
                msg.setText("未接来电");
                lastPhone = null;
                currentPhoneState = -1;
            } else {
                return;
            }
        }
        send(msg);
    }

    private String lastPhone;

    int lastPhoneState;

    private void send(NotificationEntity msg) {
        if (DeviceService.instance != null && DeviceService.instance.mConnectServer != null) {
            DeviceService.instance.mConnectServer.send(msg);
        }
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
    }
}

